import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Switch,
  InputNumber,
  Select,
  Upload,
  message,
  Tabs,
  Row,
  Col,
  Space,
  Divider,
  Alert,
  Typography,
} from 'antd';
import {
  SaveOutlined,
  UploadOutlined,
  ReloadOutlined,
  SettingOutlined,
  SecurityScanOutlined,
  MailOutlined,
  CloudUploadOutlined,
  DatabaseOutlined,
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import adminApi from '@/api/admin-api';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface SystemSettings {
  // 基础设置
  site_name: string;
  site_description: string;
  contact_email: string;
  
  // 功能设置
  enable_registration: boolean;
  max_cards_per_user: number;
  
  // 安全设置
  password_min_length: number;
  session_timeout: number;
}

const Settings: React.FC = () => {
  const [basicForm] = Form.useForm();
  const [securityForm] = Form.useForm();
  const [emailForm] = Form.useForm();
  const [storageForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');

  // 获取系统设置
  const fetchSettings = async () => {
    setLoading(true);
    try {
      const response = await adminApi.systemManagement.adminSystemSettings();
      const settings = response.data;
      
      // 设置表单值
      basicForm.setFieldsValue(settings);
      securityForm.setFieldsValue(settings);
      
    } catch (error) {
      message.error('获取设置失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSettings();
  }, []);

  // 保存设置
  const handleSave = async (formName: string, values: any) => {
    setLoading(true);
    try {
      await adminApi.systemManagement.adminSystemSettingsUpdate(values);
      message.success('设置保存成功');
    } catch (error) {
      message.error('保存失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 文件上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    action: '/api/upload',
    headers: {
      authorization: 'Bearer ' + localStorage.getItem('token'),
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  // 测试邮件配置
  const testEmailConfig = async () => {
    try {
      const values = await emailForm.validateFields();
      console.log('Testing email config:', values);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      message.success('邮件配置测试成功');
    } catch (error) {
      message.error('邮件配置测试失败');
    }
  };

  return (
    <div>
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          {/* 基础设置 */}
          <TabPane
            tab={
              <span>
                <SettingOutlined />
                基础设置
              </span>
            }
            key="basic"
          >
            <Form
              form={basicForm}
              layout="vertical"
              onFinish={(values) => handleSave('basic', values)}
            >
              <Row gutter={24}>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="site_name"
                    label="网站名称"
                    rules={[{ required: true, message: '请输入网站名称' }]}
                  >
                    <Input placeholder="请输入网站名称" />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="contact_email"
                    label="联系邮箱"
                    rules={[
                      { required: true, message: '请输入联系邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' },
                    ]}
                  >
                    <Input placeholder="请输入联系邮箱" />
                  </Form.Item>
                </Col>
              </Row>
              
              <Form.Item
                name="site_description"
                label="网站描述"
                rules={[{ required: true, message: '请输入网站描述' }]}
              >
                <TextArea
                  rows={3}
                  placeholder="请输入网站描述"
                  showCount
                  maxLength={200}
                />
              </Form.Item>

              <Row gutter={24}>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="enable_registration"
                    label="允许用户注册"
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="max_cards_per_user"
                    label="每用户最大卡片数"
                    rules={[{ required: true, message: '请输入每用户最大卡片数' }]}
                  >
                    <InputNumber
                      min={1}
                      max={10000}
                      style={{ width: '100%' }}
                      placeholder="请输入每用户最大卡片数"
                    />
                  </Form.Item>
                </Col>
              </Row>

              <div style={{ textAlign: 'right' }}>
                <Space>
                  <Button icon={<ReloadOutlined />} onClick={fetchSettings}>
                    重置
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={<SaveOutlined />}
                    loading={loading}
                  >
                    保存设置
                  </Button>
                </Space>
              </div>
            </Form>
          </TabPane>

          {/* 安全设置 */}
          <TabPane
            tab={
              <span>
                <SecurityScanOutlined />
                安全设置
              </span>
            }
            key="security"
          >
            <Form
              form={securityForm}
              layout="vertical"
              onFinish={(values) => handleSave('security', values)}
            >
              <Alert
                message="安全提醒"
                description="修改安全设置可能会影响用户登录体验，请谨慎操作。"
                type="warning"
                showIcon
                style={{ marginBottom: 24 }}
              />

              <Row gutter={24}>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="password_min_length"
                    label="密码最小长度"
                    rules={[{ required: true, message: '请输入密码最小长度' }]}
                  >
                    <InputNumber
                      min={6}
                      max={20}
                      style={{ width: '100%' }}
                      placeholder="密码最小长度"
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="session_timeout"
                    label="会话超时时间（秒）"
                    rules={[{ required: true, message: '请输入会话超时时间' }]}
                  >
                    <InputNumber
                      min={300}
                      max={86400}
                      style={{ width: '100%' }}
                      placeholder="会话超时时间"
                    />
                  </Form.Item>
                </Col>
              </Row>

              <div style={{ textAlign: 'right' }}>
                <Space>
                  <Button icon={<ReloadOutlined />} onClick={fetchSettings}>
                    重置
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={<SaveOutlined />}
                    loading={loading}
                  >
                    保存设置
                  </Button>
                </Space>
              </div>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default Settings;